<?php
// +----------------------------------------------------------------------
// |优惠券
// +----------------------------------------------------------------------
// |Data:2016-06-25 19:11
// +----------------------------------------------------------------------
// |Author: 吕志雄 <870923001@qq.com>
// +----------------------------------------------------------------------
namespace Wap\Controller;
use Common\Controller\CommonController;

class CouponsController extends CommonController{
    private $_model;
    protected function _initialize(){
        parent::_initialize();
        $this->_model = D('Common/Coupons');
    }

    /**
     * 列表
     */
    public function index(){
        $map = $this->search();
        $list = $this->_model->getUserRecordList($map);
        foreach($list['data'] as &$val){
            $shopDetail = D('Common/Shop')->detail($val['shop_id']);
            $val['shopTitle'] = $shopDetail['title'];
        }
        $this->assign($list);
        $this->display();
    }

    private function search(){
        $map = array();
        $map['cr.uid'] = $this->uid;
        $map['is_use'] = 2;
        $map['is_overdue'] = 2;
        $map['is_del'] = 2;
        $map['end_time'] = array('gt',time());
        return $map;
    }

    /**
     * 领取优惠券
     */
    public function receive(){
        $id = I('post.id');
        empty($id) && $this->returnData('请选择操作项！');
        $isHas = $this->_model->hasRecord($id,$this->uid);
        !empty($isHas) && $this->returnData('您已经领取过了！');
        $detail = $this->_model->detail($id);
        empty($detail) && $this->returnData('该记录不存在！');
        if(empty($detail['store'])) $this->returnData('该优惠券已领取完！');

        $data = array(
            'coupons_id'=>$id,
            'uid'=>$this->uid,
            'receive_time'=>time(),
            'end_time'=>$detail['ext_time'],
            'is_use'=>2,
            'is_overdue'=>2
        );
        $result = $this->_model->addRecord($data);
        if($result){
            $this->returnData('领取成功！',1);
        }else{
            $this->returnData('领取失败！');
        }
    }

    /**
     * 规则页面
     */
    public function rules(){
        $this->display();
    }
}
?>